package com.cloud.point.concurrent.general;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import lombok.extern.slf4j.Slf4j;

/**
 * 线程的创建方法
 *
 * @author 24373
 * @version 1.0
 * @date 2024-06-13 12:08
 */
@Slf4j
public class TestCreateThread {

    public static void main(String[] args) throws InterruptedException {
        /**
         * 1. thread搭配Runnable实现
         */
        new Thread(() -> {
            log.info("线程启动");
        }, "thread-a").start();

        /**
         * 2. Callable实现，在线程结束后可以获取一个返回值
         */
        FutureTask<String> task = new FutureTask<>(() -> {
            log.info("线程2启动");
            return "hello";
        });
        /**
         * FutureTask实现了runnable接口，可以作为参数传递给thread构造器
         */
        new Thread(task).start();
        try {
            // 阻塞等待线程执行完毕，获取返回值
            String result = task.get();
            log.info("线程2执行完毕:{}", result);
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

}
